package edu.xhu.homepage.bloomFilter;

import com.google.common.hash.*;
import com.google.common.primitives.Longs;
import edu.xhu.utils.thread.BiliUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class BloomFilter<T> {
    private static final long SIZE = 20_000; // 10万位,太大,长度是16000,目前只支持2000x8=16000个视频
    private final int numHashFunctions;
    private final Funnel<T> funnel;
    private final String bitMapKey;


    public BloomFilter(int numHashFunctions, Funnel<T> funnel) {
        this.numHashFunctions = numHashFunctions;
        this.funnel = funnel;
        this.bitMapKey = "bloom:" + BiliUserThreadLocalUtil.getUser().getUserId();

    }

    private long bitSize() {
        return SIZE;
    }


    private long lowerEight(byte[] bytes) {
        return Longs.fromBytes(bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2], bytes[1], bytes[0]);
    }

    private long upperEight(byte[] bytes) {
        return Longs.fromBytes(bytes[15], bytes[14], bytes[13], bytes[12], bytes[11], bytes[10], bytes[9], bytes[8]);
    }

    public Map<String, Object> getParams(T data) {
        Map<String, Object> map = new HashMap<>();
        long bitSize = bitSize();
        byte[] bytes = Hashing.murmur3_128().hashObject(data, funnel).asBytes();
        long hash1 = this.lowerEight(bytes);
        long hash2 = this.upperEight(bytes);
        map.put("bitSize", bitSize);
        map.put("hash1", hash1);
        map.put("hash2", hash2);
        map.put("numHashFunctions", numHashFunctions);
        map.put("bitMapKey", this.bitMapKey);
        return map;
    }

}

